<script setup lang="ts">
import { onMounted, ref } from 'vue'
import router from '@/router/index'
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { useMainLogin } from '@/store/user'
import { getCodeImg } from "@/api/login";
import '@styles/login.css'
import { to } from 'await-to-js';
import { ElNotification } from 'element-plus'
import { LoginData, TenantVO } from '@/api/types';

const dlFlag = ref<boolean>(true)
const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: 'admin',
  password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: ''
} as LoginData);
const useLogin = useMainLogin()
const errorflage = ref<boolean>(false)
const codeUrl = ref('');
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const redirect = ref('/');

onMounted(() => {
  getCookie()
  getCode();
})

const getCookie = () => {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get('rememberMe')
  loginForm.value.username = username === undefined ? loginForm.value.username : username,
  loginForm.value.password = password === undefined ? loginForm.value.password : decrypt(password),
  loginForm.value.rememberMe = rememberMe === undefined ? false : Boolean(rememberMe)
}

const handleLogin = async () => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '登录中，请稍后',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  if(loginForm.value.username!=''&&loginForm.value.password!='') {
    if (loginForm.value.rememberMe) {
      Cookies.set("username", loginForm.value.username, { expires: 11 });
      Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
      Cookies.set('rememberMe', loginForm.value.rememberMe, { expires: 30 });
    } else {
      Cookies.remove("username");
      Cookies.remove("password");
      Cookies.remove('rememberMe');
    }
  }
  if(loginForm.value.username!=''&&loginForm.value.password!='') {
      // 调用action的登录方法
      const [err] = await to(useLogin.Login(loginForm.value));
      if (!err) {
        await router.push("/home")
        loadingInstance.close()
      } else {
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCode();
          loadingInstance.close()
        }
      }
  }
}

/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const trialLogin = () => {
  useLogin.Login({
    tenantId: '000000',
    username: 'admin',
    password: 'admin123',
    rememberMe: false,
    code: '',
    uuid: ''
  }).then(() => {
    router.push("/home")
    // ElMessage.warning('使用公众账号登录，请勿上传隐私数据')
    ElNotification({
      title: '提示',
      message: '使用公众账号登录，请勿上传隐私数据',
      type: 'warning',
    })
  })
}

const gotoAgree = (type) => {
  let isUser
  if (type == 'user') {
    isUser = true
  } else {
    isUser = false
  }
  const c = router.resolve({
    path: "/agreement",
    query: {  isUserAgree: isUser }
  });
  window.open(c.href, "_blank");
}
</script>

<template>
  <div class="loginBG">
    <div class="login_box"></div>
    <div class="login_box-content">
      <div class="login_logo"><span>L</span>IDU</div>
      <div class="login_title">登录立度时空</div>
      <form>
        <div class="Tabs">
          <div class="zh" v-show="dlFlag">
            <div class="user-box">
              <label for="">账号</label>
              <input :class="loginForm.username!=''?'active':''" type="text" v-model="loginForm.username">
              <!-- <label :class="loginForm.username!=''?'active':''">账号</label> -->
              <div v-show="errorflage" style="font-size: 12px;color: #ff0000;">* 您的账号码格式错误，请检查后重新提交。</div>
            </div>
            <div class="user-box">
              <label for="">密码</label>
              <input :class="loginForm.password!=''?'active':''" type="password" v-model="loginForm.password" @keyup.enter.native="handleLogin" autocomplete="new-password">
              <!-- <label :class="loginForm.password!=''?'active':''">密码</label> -->
            </div>

            <div class="user-box">
              <label for="">验证码</label>
              <div style="display: flex;box-sizing: border-box;width: 100%;">
                <input style="flex:1;width: 60%;" :class="loginForm.code!=''?'active':''" type="text" v-model="loginForm.code" placeholder="请输入验证码" @keyup.enter.native="handleLogin">
                <div class="login-code">
                  <img :src="codeUrl" class="login-code-img" @click="getCode" />
                </div>
              </div>
            </div>

            <!-- <div class="tooltip_box-login" @click="loginForm.rememberMe = !loginForm.rememberMe">
              <label class="container">
                <input type="checkbox" :checked="loginForm.rememberMe" @click="loginForm.rememberMe = !loginForm.rememberMe">
                <svg viewBox="0 0 64 64" height="1rem" width="1rem">
                  <path d="M 0 16 V 56 A 8 8 90 0 0 8 64 H 56 A 8 8 90 0 0 64 56 V 8 A 8 8 90 0 0 56 0 H 8 A 8 8 90 0 0 0 8 V 16 L 32 48 L 64 16 V 8 A 8 8 90 0 0 56 0 H 8 A 8 8 90 0 0 0 8 V 56 A 8 8 90 0 0 8 64 H 56 A 8 8 90 0 0 64 56 V 16" pathLength="575.0541381835938" class="path"></path>
                </svg>
              </label>
              <span :class="loginForm.rememberMe?'rememberActive':''">记住密码</span>
            </div> -->
          </div>
        </div>
      </form>
      <div class="login_footer">
        <button class="login_btn" @click="handleLogin">登录</button>
      </div>
      <div class="footer_agreement">
        <p></p>登录或完成注册即代表你同意<p @click="gotoAgree('user')">用户协议</p>和<p @click="gotoAgree('privacy')">隐私协议</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-code-img {
  height: 40px;
  padding-left: 12px;
}
</style>
